using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.Streaming;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Excel.Entity;
using T.FAS.Runtime.Metadata.Entity;

namespace T.FAS.Runtime.Excel.Service
{
    public static class FileUtil
    {
        /// <summary>
        /// DefaultExcel
        /// </summary>       
        public const string DefaultExcel = "xlsx";
        /// <summary>
        /// 创建本地文件 单元测试用
        /// </summary>
        /// <param name = "fileName"></param>
        /// <param name = "byteContent"></param>
        public static void CreateFile(string fileName, byte[] byteContent)
        {
            using (FileStream fs = new FileStream(fileName + "." + DefaultExcel, FileMode.Create))
            {
                BinaryWriter w = new BinaryWriter(fs);
                w.Write(byteContent);
                fs.Close();
            }
        }

        /// <summary>
        /// 获取Base64类型
        /// </summary>
        /// <param name = "type"></param>
        /// <returns></returns>
        public static string GetBase64Type(string type)
        {
            switch (type)
            {
                case "xls":
                    return "data:application/vnd.ms-excel;base64,";
                case "xlsx":
                    return "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
                default:
                    throw new FasException(ExcelConstCode.InValidParam, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetTextFormatted("T_FAS_fasr_Excel_1476229719", "不支持的Excel文件类型:{0}", type)}");
            }
        }
        /// <summary>
        /// 删除一个图片，删除图片要使用相对路径
        /// </summary>
        /// <returns></returns>
        public static void DelResult(List<Resource> resources)
        {
            try
            {
                //图片的相对路径
                string json = JsonConvert.SerializeObject(resources);
                HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
                using (HttpClient httpClient = new HttpClient())
                {
                    //以下为Session校验方式   
                    httpClient.DefaultRequestHeaders.Add("SessionId", "00000000-0000-0000-0000-000000000000");
                    using (HttpResponseMessage response = httpClient.PostAsync(ConfigUtil.Instance.ResourceAPIDomain + "/api/resource/DeleteResourceBatch", content).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        //返回结果码
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 获取文件IWorkbook
        /// </summary>
        /// <returns></returns>
        public static IWorkbook GetLocalWorkbook(string filePath)
        {
            string suffix = Path.GetExtension(filePath).ToLower();
            IWorkbook workbook;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                if (suffix == ".xls")
                    workbook = new HSSFWorkbook(fs);
                else if (suffix == ".xlsx")
                    workbook = new XSSFWorkbook(fs);
                else
                    throw new FasException(ExcelConstCode.InValidParam, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetTextFormatted("T_FAS_fasr_Excel_1476229719", "不支持的Excel文件类型:{0}", suffix)}");
            }

            return workbook;
        }

        /// <summary>
        /// 初始化文件IWorkbook
        /// </summary>
        /// <returns></returns>
        public static IWorkbook GetWorkbook()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), "poifiles");
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            return new SXSSFWorkbook();
        }
        /// <summary>
        /// 获取文件IWorkbook
        /// </summary>
        /// <returns></returns>
        public static IWorkbook GetWorkbook(Entity.ImportTask importTask)
        {
            string suffix = Path.GetExtension(importTask.FileURL).ToLower();
            IWorkbook workbook;
            using (HttpClient httpClient = new HttpClient())
            {
                var url = ConfigUtil.Instance.ResourceAPIDomain + Path.AltDirectorySeparatorChar + importTask.FileURL;
                //下载图片的地址，发送请求
                using (HttpResponseMessage response = httpClient.GetAsync(url).Result)
                {
                    response.EnsureSuccessStatusCode();
                    using (Stream stream = response.Content.ReadAsStreamAsync().Result)
                    {
                        importTask.FileMD5 = "";
                        importTask.FileSize = (stream.Length / 1024) + "KB";
                        try
                        {
                            switch (suffix)
                            {
                                case ".xls":
                                    workbook = new HSSFWorkbook(stream);
                                    break;
                                case ".xlsx":
                                    workbook = new XSSFWorkbook(stream);
                                    break;
                                default:
                                    throw new FasException(ExcelConstCode.InValidParam, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetTextFormatted("T_FAS_fasr_Excel_1476229719", "不支持的Excel文件类型:{0}", suffix)}");
                            }
                        }
                        catch (Exception e)
                        {
                            throw new FasException(ExcelConstCode.InValidParam, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetTextFormatted("T_FAS_fasr_Excel_1873446774", "文件转换失败, msg:{0}", e)}", e);
                        }
                    }
                }
            }

            return workbook;
        }
        /// <summary>
        /// 初始化文件IWorkbook xls为HSSFFormulaEvaluator
        /// </summary>
        /// <returns></returns>
        public static IFormulaEvaluator GetEvaluator(IWorkbook work)
        {
            return new XSSFFormulaEvaluator(work);
        }
        /// <summary>
        /// 加载文件
        /// </summary>
        /// <returns></returns>
        public static void LoadFile(string fileURL)
        {
            using (HttpClient httpClient = new HttpClient())
            {

                var url = ConfigUtil.Instance.ResourceAPIDomain + Path.AltDirectorySeparatorChar + fileURL;
                //下载图片的地址，发送请求
                using (HttpResponseMessage response = httpClient.GetAsync(url).Result)
                {
                    response.EnsureSuccessStatusCode();
                }
            }
        }
    }
}